Conditional Statements
Tags: #◇Code Snippets #◇CCPROG1 #◇Control Flow #◇C #◇M5
◇Overview
Conditional statements, or selection structures, allow a program to make decisions and execute different blocks of code based on whether a specified condition evaluates to true or false.
◇Key Definitions
Condition: A logical expression that evaluates to true (non-zero) or false (zero). if Statement: Executes a block of code if its condition is true. else Statement: Executes a block of code if the preceding if condition is false. switch Statement: Allows a variable to be tested for equality against a list of values.
◇Code Implementation
#include <stdio.h>
int main() {
int grade = 85;
// if-else if-else structure
if (grade >= 90) {
printf("A\n");
} else if (grade >= 80) {
printf("B\n");
} else if (grade >= 70) {
printf("C\n");
} else {
printf("F\n");
}
// switch statement
char letter = 'B';
switch (letter) {
case 'A':
printf("Excellent\n");
break;
case 'B':
printf("Good\n");
break;
default:
printf("Needs Improvement\n");
}
return 0;
}
◇Syntax Breakdown
if (condition): The code block inside {} runs if condition is true. else if (condition): Checked only if the previous if was false. switch(variable): Evaluates variable. case 'X':: If variable equals 'X', execute following code. break;: Exits the switch block, preventing fall-through to the next case.
◇Common Pitfalls
Forgetting the break; statement in a switch, which causes "fall-through" execution. Using = (assignment) instead of == (equality check) inside an if condition. E.g., if (x = 5) evaluates to true because 5 is non-zero, and it changes x to 5.
◇References & Navigation
- Previous Topic: ◇User-defined Functions
- Next Topic: ◇Iterative Statements in C
- Related Notes: ◇Statement Level Control Structures, ◇Conditionals
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
What is the output of the following C code snippet if int x = 0;?
if (x = 5) printf("True"); else printf("False");
In a C switch statement, what happens when a matching case block omits the break; statement?
Which of the following data types CANNOT be used as the controlling expression of a switch statement in standard C?
In an if - else if - else ladder, when is the final else block executed?
With which if does the else pair in the nested statement if (a > 0) if (b > 0) printf("1"); else printf("2");?